/* eslint-disable react/forbid-prop-types */
/**
 * @file 数据详情
 * @author liushuang04@baijaihulian.com
 * @date 2019-11-19
 */

import React, {Component} from 'react';
import {DownOutlined, UpOutlined} from '@ant-design/icons';
import {Form} from '@ant-design/compatible';
import {Row, Col, Input, DatePicker, Select, Spin, Button, message, Tooltip} from 'antd';
// eslint-disable-next-line import/extensions
import '@ant-design/compatible/assets/index.css';
import PropTypes from 'prop-types';
import debounce from 'lodash/debounce';
import axios from 'axios';

import {fetchSelection} from '~/service/reports';
import {isTimeRange, INPUT_TYPE_ENUM, isTimePoint} from './dateRanges';
import './index.styl';
import {buildPermission} from './helps';

const {CancelToken} = axios;
const {RangePicker} = DatePicker;
const {Option} = Select;
// 默认显示3行共9个
const DEFAULT_SIZE = 9;
// 根据type判断参数时间格式
let timeRangeType = null;
let classId = 0;
class SearchForm extends Component {
    static propTypes = {
        data: PropTypes.array.isRequired,
        form: PropTypes.shape({
            resetFields: PropTypes.func,
            getFieldDecorator: PropTypes.func,
            setFieldsValue: PropTypes.func,
            getFieldValue: PropTypes.func,
            getFieldsValue: PropTypes.func,
            validateFields: PropTypes.func,
        }).isRequired,
        onSearch: PropTypes.func.isRequired,
        isLoading: PropTypes.bool.isRequired,
    };

    constructor(props) {
        super(props);
        this.handleFetchSelection = debounce(this.handleFetchSelection, 500, {
            leading: true
        });
        this.selectCancelTokenSource = [];
        this.state = {
            dimensions: [],
            fetching: false,
            showMore: false,
        };
    }

    // 显示渲染
    getFields = () => {
        const {form} = this.props;
        const {data: options} = this.props;
        const {getFieldDecorator} = form;
        const {dimensions, fetching, showMore} = this.state;
        return options.map((item, index) => {
            if (item.dimensionName === '课节序号') {
                classId = item.dimensionId;
            }
            if (isTimeRange(item.isinput)) {
                timeRangeType = item.isinput;
                let showTime = false;
                let format = 'YYYY-MM-DD';
                if (item.isinput === INPUT_TYPE_ENUM.MINUTE) {
                    showTime = {
                        format: 'HH:mm'
                    };
                    format = 'YYYY-MM-DD HH:mm';
                }
                else if (item.isinput === INPUT_TYPE_ENUM.HOUR) {
                    showTime = {
                        format: 'HH'
                    };
                    format = 'YYYY-MM-DD HH';
                }
                // 天 周 月 总是显示到日期
                else {
                    showTime = false;
                    format = 'YYYY-MM-DD';
                }
                return (
                    <Col span={8} key={item.dimensionId}>
                        <Form.Item label={item.dimensionName}>
                            {getFieldDecorator(`${item.dimensionId}`, {
                                initialValue: item.filterItems,
                            })(
                                <RangePicker
                                    style={{
                                        width: '100%'
                                    }}
                                    showTime={showTime}
                                    format={format}
                                    onChange={this.handleTimeChange}
                                />
                            )}
                        </Form.Item>
                    </Col>
                );
            }
            if (isTimePoint(item.isinput)) {
                return (
                    <Col span={8} key={item.dimensionId}>
                        <Form.Item label={item.dimensionName}>
                            {/* 把dimensionId作为form的字段，用来存储filterItem */}
                            {getFieldDecorator(`${item.dimensionId}`, {
                                initialValue: item.filterItems[0],
                            })(
                                <DatePicker
                                    style={{
                                        width: '100%'
                                    }}
                                    onChange={this.handleTimeChange}
                                />
                            )}
                        </Form.Item>
                    </Col>
                );
            }
            if (item.isinput === 0 || item.isinput === 3) {
                return (
                    <Col span={8} key={item.dimensionId} className={index >= DEFAULT_SIZE && !showMore ? 'hidden' : ''}>
                        <Form.Item label={item.dimensionName}>
                            {getFieldDecorator(`${item.dimensionId}`, {
                                initialValue: item.filterItems,
                            })(
                                <Select
                                    mode={item.isinput === 0 ? 'multiple' : false} placeholder="展示50个选项，其余请搜索"
                                    notFoundContent={fetching ? <Spin size="small" /> : null}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    onDropdownVisibleChange={this.handleFetchSelection.bind(this, item)}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    onSelect={this.handleSelectOne.bind(this, item)}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    onSearch={this.handleFetchSelection.bind(this, item)}
                                    allowClear showSearch
                                    filterOption={false}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                >
                                    {item.isinput === 0 ? <Option key={0} value="全部">全部</Option> : null}
                                    {
                                        dimensions.map(i => (
                                            <Option key={i} value={i}>
                                                <Tooltip title={i} placement="topLeft">
                                                    {i}
                                                </Tooltip>
                                            </Option>
                                        ))
                                    }
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                );
            }
            // input输入框
            return (
                <Col span={8} key={item.dimensionId} className={index >= DEFAULT_SIZE && !showMore ? 'hidden' : ''}>
                    <Form.Item label={item.dimensionName}>
                        {getFieldDecorator(`${item.dimensionId}`, {
                            initialValue: item.filterItems[0] || '',
                        })(
                            <Input placeholder="输入查询关键词" allowClear />
                        )}
                    </Form.Item>
                </Col>
            );
        });
    };

    // 勾选
    handleSelectOne = (item, e) => {
        const {form} = this.props;
        const selectValue = form.getFieldValue(`${item.dimensionId}`);
        if (e === '全部') {
            this.props.form.setFieldsValue({[`${item.dimensionId}`]: e});
        }
        else if (selectValue.indexOf('全部') > -1) {
            this.props.form.setFieldsValue({[`${item.dimensionId}`]: e});
        }
    };

    // 当日期控件的值发生改变时,重置课节(好课行课)和课节序号(高途行课)
    handleTimeChange = () => {
        const {xingkeSign} = this.props;
        let permissions = [];
        this.props.form.validateFields((error, fieldsValue) => {
            if (error) {
                return;
            }
            permissions = buildPermission(fieldsValue, timeRangeType);
        });
        // 对于课节(好课行课),恒为2666
        permissions = permissions.filter(item => item.dimensionId !== '2666');
        this.props.form.resetFields('2666');

        // 对于课节序号(高途行课),不是一个恒量
        if (xingkeSign === 'gaotuXingke') {
            permissions = permissions.filter(item => item.dimensionId !== `${classId}`);
            this.props.form.resetFields(`${classId}`);
        }
    };

    // 查询
    handleSearch = e => {
        e.preventDefault();
        this.props.form.validateFields((error, fieldsValue) => {
            if (error) {
                return;
            }
            const permList = buildPermission(fieldsValue, timeRangeType);
            this.props.onSearch(permList);
        });
    };

    // 重置
    handleReset = () => {
        this.props.form.resetFields();
    };

    // 获取数据
    getSelectOption = params => {
        const source = CancelToken.source();
        this.selectCancelTokenSource.push(source);
        for (let i = 0; i < this.selectCancelTokenSource.length - 1; i++) {
            this.selectCancelTokenSource[i].cancel('请求取消');
        }
        fetchSelection(params, source.token)
            .then(res => {
                const {data = []} = res;
                this.setState({
                    dimensions: data,
                    fetching: false,
                });
            })
            .catch(error => {
                this.setState({
                    dimensions: [],
                    fetching: false,
                });
                message.error('获取数据错误');
                console.error(error);
            });
    };

    // 获取维度列表(筛选项)
    handleFetchSelection = (item, e) => {
        const {dimensionId, taskId} = item;
        const {id: viewId, xingkeSign} = this.props;
        const pager = {pageNum: 1, pageSize: 50};
        const searchKey = typeof e === 'string' ? e.trim() : '';
        let permissions = [];
        this.props.form.validateFields((error, fieldsValue) => {
            if (error) {
                return;
            }
            permissions = buildPermission(fieldsValue, timeRangeType);
        });
        permissions = permissions.filter(item => item.dimensionId.toString() !== dimensionId.toString()
            && item.filterItems.length > 0);
        // 如果select被下拉
        if (e) {
            this.setState({fetching: true, dimensions: []});
            // 对于好课行课“课节”的逻辑, 判断并初始化课节(当“课节”控件的dimensionId恒为2666时,以下判断合理)
            permissions = permissions.filter(item => item.dimensionId !== '2666');
            this.props.form.resetFields('2666');
            if (dimensionId === 2666) {
                if (permissions.length < 1) {
                    message.warning('请先选择班级Id或者辅导班Id');
                    return;
                }
            }
            // 对于高途行课“课节序号”的逻辑, 判断并初始化课节序号(高途“课节序号”不恒为一个数)
            if (xingkeSign === 'gaotuXingke') {
                permissions = permissions.filter(item => item.dimensionId !== `${classId}`);
                this.props.form.resetFields(`${classId}`);
                if (dimensionId === classId) {
                    if (permissions.length < 1) {
                        message.warning('请先输入其他数据');
                        return;
                    }
                }
            }

            this.getSelectOption({dimensionId, viewId, taskId, pager, searchKey, permissions});
        }
    };

    handleShowMore = () => {
        this.setState(prevState => ({
            showMore: !prevState.showMore
        }));
    };

    render() {
        const {isLoading, data: options} = this.props;
        const {showMore} = this.state;
        return (
            <Form class="ant-advanced-search-form" onSubmit={this.handleSearch}>
                <Row gutter={24} type="flex">
                    {this.getFields()}
                </Row>
                <Row>
                    <Col span={8} />
                    <Col span={8} style={{textAlign: 'center', cursor: 'pointer'}} onClick={this.handleShowMore}>
                        {
                            options.length > DEFAULT_SIZE && (showMore ? (
                                <>
                                    <span>收起</span>
                                    <UpOutlined />
                                </>
                            ) : (
                                <>
                                    <span>展开</span>
                                    <DownOutlined />
                                </>
                            ))
                        }
                    </Col>
                    <Col span={8} style={{textAlign: 'right'}}>
                        <Button type="primary" htmlType="submit" loading={isLoading}>
                            查询
                        </Button>
                        <Button style={{marginLeft: 8}} onClick={this.handleReset}>
                            重置
                        </Button>
                    </Col>
                </Row>
            </Form>
        );
    }
}

const WrapperForm = Form.create({name: 'searchForm'})(SearchForm);
export default WrapperForm;
